import { _decorator, AudioClip, AudioSource, Component, EventKeyboard, input, Input, instantiate, KeyCode, Label, Node, Prefab, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Farm')
export class Farm extends Component {
    @property(Prefab)
    animalPrefab: Prefab = null;

    @property(Node)
    animalLayerNode: Node = null;

    @property(Node)
    treeNode: Node = null;

    @property(Node)
    houseNode: Node = null;

    @property(Label)
    amountLbl: Label = null;

    @property(AudioClip)
    crowClip: AudioClip = null;

    audioSource: AudioSource = null;

    _animalNode: Node;
    _amount: number = 0;

    protected onLoad(): void {
        input.on(Input.EventType.KEY_DOWN, this.onKeydown, this);

        this.audioSource = this.node.getComponent(AudioSource);
    }

    onKeydown(event: EventKeyboard) {
        switch (event.keyCode) {
            case KeyCode.SPACE:
                this.animalRunToHouse();
                break;
        }
    }

    start() {
        // this._animalNode = instantiate(this.animalPrefab);
        // this._animalNode.active = true;
        // this._animalNode.setParent(this.animalLayerNode);
        // this._animalNode.setPosition(this.treeNode.position.x, 0);
    }

    update(deltaTime: number) {

    }

    animalRunToHouse() {
        // this._animalNode.setPosition(this.treeNode.position.x, 0);
        // tween(this._animalNode)
        //     .by(2, { position: new Vec3(this.houseNode.position.x - this.treeNode.position.x, 0) })
        //     .start();

        let animalNode = instantiate(this.animalPrefab);
        animalNode.active = true;
        animalNode.setParent(this.animalLayerNode);
        animalNode.setPosition(this.treeNode.position.x, 0);
        tween(animalNode)
            .by(2, { position: new Vec3(this.houseNode.position.x - this.treeNode.position.x, 0) })
            .call(() => {
                this._amount++;
                this.amountLbl.string = `${this._amount}`;
            })
            .start();
        let bodyNode = animalNode.getChildByName("Body");
        bodyNode.setPosition(Vec3.ZERO)
        tween(bodyNode)
            .by(0.2, { position: new Vec3(0, 180) })
            .by(0.2, { position: new Vec3(0, -180) })
            .union()
            .repeatForever()
            .start()
        this.audioSource.playOneShot(this.crowClip);
    }
}


